package cn.jiemusic.utils;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.jiemusic.common.CustomException;
import cn.jiemusic.contexts.UserContext;
import jakarta.servlet.http.HttpServletRequest;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

public class CodeUtils {
    public static String getLineCaptcha(HttpServletRequest req) throws IOException {
        //设置验证码宽高，字数，干扰线条
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 50, 4, 100);
        //设置背景颜色
        lineCaptcha.setBackground(Color.decode("#f1f1f1"));

        //存入请求
        req.getSession().setAttribute("code", lineCaptcha.getCode());

        BufferedImage image = lineCaptcha.getImage();

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", stream);
        byte[] imageBytes = stream.toByteArray();

        return Base64.getEncoder().encodeToString(imageBytes);
    }

    public static void checkCode(HttpServletRequest req, String code) {
        String uCode = req.getSession().getAttribute("code").toString();
        if (!code.equalsIgnoreCase(uCode)) throw new CustomException("验证码错误");
    }

    public static void checkECode(HttpServletRequest req, String code) {
        String eCode = req.getSession().getAttribute("eCode").toString();
        if (!code.equalsIgnoreCase(eCode)) throw new CustomException("验证码错误");
    }
}
